﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.IO;

using ESOL.Common.Entity;
using ESOL.Business.Sys;
using BPM.Foundation.PWDB;

namespace ESOL.Services
{
    [ServiceBehavior(UseSynchronizationContext = false,
    ConcurrencyMode = ConcurrencyMode.Multiple,
    InstanceContextMode = InstanceContextMode.PerCall)]
    public class SysService : ISysService
    {
        public bool TestConnect()
        {
            return true;
        }

        public DateTime GetSysCurTime()
        {
            return DateTime.Now;
        }

        public SysService()
        {
        }

        public SysInfoEntity AddSysInfo(SysInfoEntity sysInfo)
        {
            try
            {
                sysInfo.CreatedDate = DateTime.Now;
                return SysInfoBs.InsertSysInfo(sysInfo);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool UpdateSysInfo(SysInfoEntity sysInfo)
        {
            try
            {
                sysInfo.UpdatedDate = DateTime.Now;
                return SysInfoBs.UpdateSysInfo(sysInfo);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public DataSet GetSysInfoPages(int pageIndex, int pageCount)
        {
            try
            {
                return SysInfoBs.GetSysInfoPages(pageIndex, pageCount);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public DataSet GetSysFcByCondition(string rowCount, string condition)
        {
            try
            {
                return SysFcBs.GetSysFcByCondition(rowCount, condition);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public SysFcEntity AddSysFc(SysFcEntity sysFc)
        {
            try
            {
                sysFc = SysFcBs.InsertSysFc(sysFc);
                return sysFc;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
            //throw new NotImplementedException();
        }

        public bool UpdateSysFc(SysFcEntity sysFc)
        {
            try
            {
                return SysFcBs.UpdateSysFc(sysFc);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public DataSet GetSysPeriodPageByFc(SysFcEntity sysFc, int pageIndex, int pageCount)
        {
            try
            {
                return SysPeriodBs.GetSysPeriodPageByFc(sysFc, pageIndex, pageCount);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public SysPeriodEntity AddSysPeriod(SysPeriodEntity SysPeriod)
        {
            try
            {
                SysPeriod = SysPeriodBs.InsertSysPeriod(SysPeriod);
                return SysPeriod;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public List<SysPeriodEntity> AddSysPeriodsByMonth(SysFcEntity sysFc, int month, int periodType)
        {
            int monthDays = DateTime.DaysInMonth(DateTime.Today.Year, month);
            List<SysPeriodEntity> sysPeriods = new List<SysPeriodEntity>();
            for (int i = 1; i <= monthDays; i++)
            {
                SysPeriodEntity sysPeriod = new SysPeriodEntity();
                sysPeriod.CalendarId = sysFc.Id;
                sysPeriod.Id = Guid.NewGuid().ToString();
                sysPeriod.IsActive = 1;
                sysPeriod.Year = DateTime.Today.Year;
                sysPeriod.Month = month;
                sysPeriod.Day = i;
                sysPeriod.PeriodType = periodType;
                sysPeriods.Add(sysPeriod);
            }
            try
            {
                SysPeriodBs.InsertSysPeriod(sysPeriods);
                return sysPeriods;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool UpdateSysPeriod(SysPeriodEntity sysPeriod)
        {
            try
            {
                return SysPeriodBs.UpdateSysPeriod(sysPeriod);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public SysWorkingPeriodEntity AddSysWorkingPeriod(SysWorkingPeriodEntity sysWorkingPeriod)
        {
            try
            {
                sysWorkingPeriod.Id = Guid.NewGuid().ToString();
                sysWorkingPeriod = SysWorkingPeriodBs.InsertSysWorkingPeriod(sysWorkingPeriod);
                return sysWorkingPeriod;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool AddSysWorkingPeriodsForPeriod(SysPeriodEntity sysPeriod, List<SysWorkingPeriodEntity> lwfp)
        {
            try
            {
                foreach (var e in lwfp)
                {
                    e.Id = Guid.NewGuid().ToString();
                    e.IsActive = 1;
                    e.PeriodId = sysPeriod.Id;
                }
                return SysWorkingPeriodBs.InsertSysWorkingPeriod(lwfp);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool AddSysWorkingPeriodsByFc(SysFcEntity sysFc, List<SysWorkingPeriodEntity> lwfp)
        {
            try
            {
                DataSet ds = SysPeriodBs.GetSysPeriodByFc(sysFc);
                List<SysWorkingPeriodEntity> source = new List<SysWorkingPeriodEntity>();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (var e in lwfp)
                    {
                        SysWorkingPeriodEntity workingPeriod = new SysWorkingPeriodEntity();
                        workingPeriod.Id = Guid.NewGuid().ToString();
                        workingPeriod.IsActive = 1;
                        workingPeriod.PeriodId = dr["ID"].ToString();
                        workingPeriod.TimeFrom = e.TimeFrom;
                        workingPeriod.TimeTo = e.TimeTo;
                        workingPeriod.ExcutingTime = e.ExcutingTime;
                        source.Add(workingPeriod);
                    }
                }
                return SysWorkingPeriodBs.InsertSysWorkingPeriod(source);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public bool UpdateSysWorkingPeriod(SysWorkingPeriodEntity sysWorkingPeriod)
        {
            try
            {
                return SysWorkingPeriodBs.UpdateSysWorkingPeriod(sysWorkingPeriod); ;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public DataSet GetWPeriod(SysPeriodEntity sysPeriod)
        {
            try
            {
                return SysWorkingPeriodBs.GetSysWorkingPeriodAll(sysPeriod);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        ////查询工作流
        //public DataSet GetWfPageByCondition(WfQueryCondition queryCondition)
        //{
        //    try
        //    {
        //        int pageIndex = 1;
        //        int PageSize = 50;
        //        if (queryCondition.txtPageIndex != null)
        //            pageIndex = queryCondition.txtPageIndex;
        //        if (queryCondition.txtPageSize != null)
        //            PageSize = queryCondition.txtPageSize;
        //        string condition = "";
        //        if (!string.IsNullOrEmpty(queryCondition.txtName))
        //        {
        //            condition += " AND wf.NAME LIKE '%" + queryCondition.txtName + "%'";
        //        }
        //        condition += " AND wf.IS_ACTIVE=" + queryCondition.cbIsActive;
        //        return SysWfBs.GetAllByCondition(pageIndex, PageSize, condition);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public DataSet GetAllSysWf()
        //{
        //    try
        //    {
        //        return SysWfBs.GetSysWfAll();
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public FrmMaintainWf GetFrmMaintainWf(string sysWfId)
        //{
        //    try
        //    {
        //        DataSet ds = SysWfBs.GetAllByCondition(1, 10, " AND wf.ID='" + sysWfId + "'");
        //        if (ds.Tables[0].Rows.Count == 0)
        //            return null;
        //        FrmMaintainWf r = new FrmMaintainWf();
        //        r.wfId = ds.Tables[0].Rows[0]["ID"].ToString();
        //        r.txtCreatedBy = ds.Tables[0].Rows[0]["CREATED_BY"].ToString();
        //        if (ds.Tables[0].Rows[0]["CREATED_DATE"] != null)
        //            r.txtCreatedDate = (DateTime)ds.Tables[0].Rows[0]["CREATED_DATE"];
        //        r.txtCreatedPerson = ds.Tables[0].Rows[0]["CREATED_PERSON"].ToString();
        //        r.txtUpdatedBy = ds.Tables[0].Rows[0]["UPDATED_BY"].ToString();
        //        if (ds.Tables[0].Rows[0]["UPDATED_DATE"] != null)
        //            r.txtUpdatedDate = (DateTime)ds.Tables[0].Rows[0]["UPDATED_DATE"];
        //        r.txtUpdatedPerson = ds.Tables[0].Rows[0]["UPDATED_PERSON"].ToString();
        //        r.txtName = ds.Tables[0].Rows[0]["NAME"].ToString();
        //        r.txtURL = ds.Tables[0].Rows[0]["URL"].ToString();
        //        r.cbIsActive = (int)ds.Tables[0].Rows[0]["IS_ACTIVE"];
        //        return r;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        ////查询SYS_TABLE
        //public DataSet GetSysTabByCondition(TabQueryCondition queryCondition)
        //{
        //    try
        //    {
        //        string condition = "";
        //        if (!string.IsNullOrEmpty(queryCondition.txtTabName))
        //        {
        //            condition += " AND tab.NAME like '%" + queryCondition.txtTabName + "%'";
        //        }
        //        if (!string.IsNullOrEmpty(queryCondition.txtFormName))
        //        {
        //            condition += " AND tab.FORM_NAME like '%" + queryCondition.txtFormName + "%'";
        //        }
        //        if (!string.IsNullOrEmpty(queryCondition.txtWfName))
        //        {
        //            condition += " AND wf.NAME like '%" + queryCondition.txtWfName + "%'";
        //        }
        //        return SysTableBs.GetAllByCondition(queryCondition.txtPageIndex, queryCondition.txtPageSize, condition);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public bool AddSysTab(SysTableEntity sysTable)
        //{
        //    try
        //    {
        //        sysTable.CreatedDate = DateTime.Now;
        //        sysTable.UpdatedDate = DateTime.Now;
        //        return SysTableBs.InsertSysTable(sysTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public bool UpdateSysTab(SysTableEntity sysTable)
        //{
        //    try
        //    {
        //        sysTable.UpdatedDate = DateTime.Now;
        //        return SysTableBs.UpdateSysTable(sysTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //public bool DelSysTab(SysTableEntity sysTable)
        //{
        //    try
        //    {
        //        return SysTableBs.DeleteSysTable(sysTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //查询菜单

        //public DataSet GetAllSecMenu()
        //{
        //    try
        //    {
        //        return SecMenuBs.GetSecMenuAll();
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new FaultException<ProcessExecutionFault>
        //            (new ProcessExecutionFault(), ex.Message);
        //    }
        //}

        //查询业务表单附件内容
        public List<SysAttachmentEntity> GetAllAttch(string formName, string rowId)
        {
            try
            {
                return SysAttachmentBs.GetSysAttachmentAllList(new SysAttachmentEntity { FormName = formName, RowId = rowId });
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? AddAttch(SysAttachmentEntity attch)
        {
            try
            {
                if (attch.Id == null)
                    return 1;
                if (attch.FormName == null)
                    return 2;
                if (attch.RowId == null)
                    return 3;
                if (attch.FileName == null)
                    return 4;
                if (attch.FilePath == null)
                    return 5;
                if (SysAttachmentBs.InsertSysAttachment(attch))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? UpdateAttch(SysAttachmentEntity attch)
        {
            try
            {
                if (attch.Id == null)
                    return 1;
                if (attch.FormName == null)
                    return 2;
                if (attch.RowId == null)
                    return 3;
                if (attch.FileName == null)
                    return 4;
                if (attch.FilePath == null)
                    return 5;
                if (SysAttachmentBs.UpdateSysAttachment(attch))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public int? DelAttch(SysAttachmentEntity attch)
        {
            try
            {
                if (attch.Id == null)
                    return 1;
                if (attch.FormName == null)
                    return 2;
                if (attch.RowId == null)
                    return 3;
                if (attch.FileName == null)
                    return 4;
                if (attch.FilePath == null)
                    return 5;
                if (SysAttachmentBs.DeleteSysAttachment(attch))
                    return null;
                else return -1;
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public FileUploadReturnMessage UploadAttach(AttachUploadMessage request)
        {
            try
            {
                var sysStFile = SysStFileBs.GetSysStFile(new SysStFileEntity { Type = request.FormName });
                string uploadFolder = sysStFile.Path;
                string dateString = DateTime.Now.ToShortDateString() + @"\";
                string fileName = request.RowID + "_" + request.FileName;
                Stream sourceStream = request.FileData;
                FileStream targetStream = null;

                if (!sourceStream.CanRead)
                {
                    return null;
                }
                uploadFolder = uploadFolder + "\\" + dateString;
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                string filePath = Path.Combine(uploadFolder, fileName);
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
                SysAttachmentEntity attch = new SysAttachmentEntity
                {
                    Id = request.ID,
                    FormName = request.FormName,
                    RowId = request.RowID,
                    FileName = request.FileName,
                    FilePath = filePath,
                    UploadBy = request.UploadBy,
                    UploadTime = DateTime.Now
                };
                if (!SysAttachmentBs.InsertSysAttachment(attch))
                    return null;
                FileUploadReturnMessage result = new FileUploadReturnMessage { FilePath = filePath };
                return result;
            }
            catch
            {
                return null;
            }
        }

        public AttachDownloadReturnMessage DownloadAttach(FileDownloadMessage request)
        {
            if (!File.Exists(request.FilePath))
                return new AttachDownloadReturnMessage { FileData = null };
            var file = Common.CommonFunctions.FileToByte(request.FilePath);
            if (file == null)
                return null;
            AttachDownloadReturnMessage result = new AttachDownloadReturnMessage { FileData = file };
            return result;
        }

        public FileUploadReturnMessage UploadFile(FileUploadMessage request)
        {
            try
            {
                var sysStFile = SysStFileBs.GetSysStFile(new SysStFileEntity { Type = request.FormName });
                string uploadFolder = sysStFile.Path;
                string savaPath = request.Type;
                string dateString = DateTime.Now.ToShortDateString() + @"\";
                string fileName = request.ID + "_" + request.Name;
                Stream sourceStream = request.FileData;
                FileStream targetStream = null;

                if (!sourceStream.CanRead)
                {
                    return null;
                }
                if (!savaPath.EndsWith("\\")) savaPath += "\\";
                uploadFolder = uploadFolder + savaPath + dateString;
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                string filePath = Path.Combine(uploadFolder, fileName);
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
                SysFileEntity file = new SysFileEntity
                {
                    Id = request.ID,
                    IsActive = 1,
                    CreatedBy = request.UploadBy,
                    CreatedDate = DateTime.Now,
                    UpdatedBy = request.UploadBy,
                    UpdatedDate = DateTime.Now,
                    FormName = request.FormName,
                    RowId = request.RowID,
                    Name = request.Name,
                    Path = filePath,
                    Type = request.Type,
                    DeptNo = request.DeptNo
                };
                if (!SysFileBs.InsertSysFile(file))
                    return null;
                FileUploadReturnMessage result = new FileUploadReturnMessage { FilePath = filePath };
                return result;
            }
            catch
            {
                return null;
            }
        }

        public FileDownloadReturnMessage DownloadFile(FileDownloadMessage request)
        {
            if (!File.Exists(request.FilePath))
                return new FileDownloadReturnMessage { FileData = null };
            var file = Common.CommonFunctions.FileToByte(request.FilePath);
            if (file == null)
                return new FileDownloadReturnMessage { FileData = null };
            FileDownloadReturnMessage result = new FileDownloadReturnMessage { FileData = file };
            return result;
        }

        public int? AddFile(SysFileEntity file)
        {
            if (file == null)
                return 1;
            if (SysFileBs.InsertSysFile(file))
                return null;
            else return -1;
        }

        public int? UpdateFile(SysFileEntity file)
        {
            if (file == null)
                return 1;
            if (SysFileBs.UpdateSysFile(file))
                return null;
            else return -1;
        }

        public int? DelFile(SysFileEntity file)
        {
            if (file == null)
                return 1;
            List<SysFilePowerEntity> sfp = SysFilePowerBs.GetAllListByFileId(file.Id);
            if (SysFileBs.DelSysFileAndPower(file, sfp))
            {
                if (File.Exists(file.Path))
                {
                    File.Delete(file.Path);
                }
                return null;
            }
            else return -1;
        }

        public int? DelFiles(List<SysFileEntity> files)
        {
            if (files == null)
                return 1;
            if (files.Count == 0)
                return 2;
            List<SysFilePowerEntity> filePowers = new List<SysFilePowerEntity>();
            foreach (var file in files)
            {
                var filePower = SysFilePowerBs.GetSysFileUserPowerAllList(file.Id);
                filePowers.AddRange(filePower);
            }
            if (SysFileBs.DelSysFilesAndPowers(files, filePowers))
            {
                foreach (var file in files)
                {
                    if (File.Exists(file.Path))
                    {
                        File.Delete(file.Path);
                    }
                }
                return null;
            }
            else return -1;
        }

        public List<SysFileEntity> GetSysFilesAllList(string rowId)
        {
            if (string.IsNullOrEmpty(rowId))
                return null;
            return SysFileBs.GetSysFileAllList(rowId);
        }

        public DataSet GetSysFilesDs(string rowId)
        {
            if (string.IsNullOrEmpty(rowId))
                return null;
            return SysFileBs.GetSysFileDs(rowId);
        }

        public DataSet GetSysFilesAllDsByCondition(FileQueryCondition queryCondition)
        {
            try
            {
                int pageIndex = 1;
                int PageSize = 50;
                if (queryCondition.txtPageIndex != null)
                    pageIndex = queryCondition.txtPageIndex;
                if (queryCondition.txtPageSize != null)
                    PageSize = queryCondition.txtPageSize;
                string condition = "";
                if (!string.IsNullOrEmpty(queryCondition.name))
                {
                    condition += " AND sf.NAME LIKE '%" + queryCondition.name + "%'";
                }
                if (!string.IsNullOrEmpty(queryCondition.type))
                {
                    condition += " AND sf.TYPE='" + queryCondition.type + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.deptNo))
                {
                    condition += " AND sf.DEPT_NO='" + queryCondition.deptNo + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.docNo))
                {
                    condition += " AND sf.DOCUMENT_NO='" + queryCondition.docNo + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.fileNo))
                {
                    condition += " AND sf.FILE_NO='" + queryCondition.fileNo + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.ver))
                {
                    condition += " AND sf.VER='" + queryCondition.ver + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.controlType))
                {
                    condition += " AND sf.CONTROL_TYPE='" + queryCondition.controlType + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.fileExistType))
                {
                    condition += " AND sf.FILE_EXISTS_TYPE='" + queryCondition.fileExistType + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.status))
                {
                    condition += " AND sf.FILE_STATUS='" + queryCondition.status + "'";
                }
                condition += " AND sf.IS_ACTIVE=" + queryCondition.isActive;
                return SysFilePowerBs.GetAllByCondition(pageIndex, PageSize, condition);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        public List<SysFilePowerEntity> GetSysFileDutyPowerByFileId(string fileId)
        {
            if (string.IsNullOrEmpty(fileId))
                return null;
            return SysFilePowerBs.GetSysFileDutyPowerAllList(fileId);
        }

        public List<SysFilePowerEntity> GetSysFileUserPowerByFileId(string fileId)
        {
            if (string.IsNullOrEmpty(fileId))
                return null;
            return SysFilePowerBs.GetSysFileUserPowerAllList(fileId);
        }

        public int? AddSysFilePower(SysFilePowerEntity filePower)
        {
            if (filePower == null)
                return 1;
            if (SysFilePowerBs.InsertSysFilePower(filePower))
                return null;
            else return -1;
        }

        public int? AddSysFilePowers(List<SysFilePowerEntity> filePowers)
        {
            if (filePowers == null)
                return 1;
            if (filePowers.Count == 0)
                return 2;
            if (SysFilePowerBs.InsertSysFilePower(filePowers))
                return null;
            else return -1;
        }

        public int? DelSysFilePowers(List<SysFilePowerEntity> filePowers)
        {
            if (filePowers == null)
                return 1;
            if (filePowers.Count == 0)
                return 2;
            if (SysFilePowerBs.DeleteSysFilePower(filePowers))
                return null;
            else return -1;
        }

        public int? DelSysFilePower(SysFilePowerEntity filePower)
        {
            if (filePower == null)
                return 1;
            if (SysFilePowerBs.DeleteSysFilePower(filePower))
                return null;
            else return -1;
        }

        public int? DelSysFileAndPower(SysFileEntity file)
        {
            if (file == null)
                return 1;
            if (string.IsNullOrEmpty(file.Id))
                return 2;
            var filePowers = SysFilePowerBs.GetSysFileUserPowerAllList(file.Id);
            if (SysFileBs.DelSysFileAndPower(file, filePowers))
            {
                return null;
            }
            else
            {
                return -1;
            }
        }

        public DataSet GetSysFilesAllDsByPowerCondition(string userNo, string[] dutyNos, FileQueryCondition queryCondition)
        {
            try
            {
                int pageIndex = 1;
                int PageSize = 50;
                if (queryCondition.txtPageIndex != null)
                    pageIndex = queryCondition.txtPageIndex;
                if (queryCondition.txtPageSize != null)
                    PageSize = queryCondition.txtPageSize;
                string condition = "";
                if (!string.IsNullOrEmpty(queryCondition.name))
                {
                    condition += " AND sf.NAME LIKE '%" + queryCondition.name + "%'";
                }
                if (!string.IsNullOrEmpty(queryCondition.type))
                {
                    condition += " AND sf.TYPE='" + queryCondition.type + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.deptNo))
                {
                    condition += " AND sf.DEPT_NO='" + queryCondition.deptNo + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.docNo))
                {
                    condition += " AND sf.DOCUMENT_NO='" + queryCondition.docNo + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.fileNo))
                {
                    condition += " AND sf.FILE_NO='" + queryCondition.fileNo + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.ver))
                {
                    condition += " AND sf.VER='" + queryCondition.ver + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.controlType))
                {
                    condition += " AND sf.CONTROL_TYPE='" + queryCondition.controlType + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.fileExistType))
                {
                    condition += " AND sf.FILE_EXISTS_TYPE='" + queryCondition.fileExistType + "'";
                }
                if (!string.IsNullOrEmpty(queryCondition.status))
                {
                    condition += " AND sf.FILE_STATUS='" + queryCondition.status + "'";
                }
                condition += " AND sf.IS_ACTIVE=" + queryCondition.isActive;
                return SysFilePowerBs.GetAllByPowerCondition(pageIndex, PageSize, userNo, dutyNos, condition);
            }
            catch (Exception ex)
            {
                throw new FaultException<ProcessExecutionFault>
                    (new ProcessExecutionFault(), ex.Message);
            }
        }

        /// <summary>
        /// 查询文件可接收的人
        /// </summary>
        /// <returns>USER_NO</returns>
        public DataSet GetFileAcceptUser(string rowId)
        {
            if (string.IsNullOrEmpty(rowId))
                return null;
            string sql = @"select distinct sfp.USER_NO 
from SYS_FILE_POWER sfp
left join SYS_FILE sf on sfp.FILE_ID=sf.ID
where sf.ROW_ID='{0}'
and sfp.DUTY_NO is null
union
select distinct u.userNo 
from SYS_FILE_POWER sfp
left join SYS_FILE sf on sfp.FILE_ID=sf.ID
left join BPMDB.dbo.PW_Duty d on sfp.DUTY_NO=d.dutyNo
left join BPMDB.dbo.PW_DepartmentDutyUserRelation du on d.dutyNo=du.dutyNo
left join BPMDB.dbo.PW_User u on du.userNo=u.userNo
where sf.ROW_ID='{0}'
and sfp.USER_NO is null";
            sql = string.Format(sql, rowId);
            return SysFileBs.GetAllDsBySql(sql);
        }

        /// <summary>
        /// 根据用户，查询可接收的文件
        /// </summary>
        /// <param name="userNo"></param>
        /// <param name="rowId"></param>
        /// <returns></returns>
        public DataSet GetAcceptFileByUserNo(string userNo, string rowId)
        {
            if (string.IsNullOrEmpty(userNo))
                return null;
            string sql = @"select distinct sf.* 
from SYS_FILE sf
left join SYS_FILE_POWER sfp on sf.ID=sfp.FILE_ID
where sfp.DUTY_NO is null and sfp.USER_NO='{0}' and sf.ROW_ID='{1}'
union
select distinct sf.*
from SYS_FILE sf
left join SYS_FILE_POWER sfp on sf.ID=sfp.FILE_ID
left join BPMDB.dbo.PW_Duty d on sfp.DUTY_NO=d.dutyNo
left join BPMDB.dbo.PW_DepartmentDutyUserRelation du on d.dutyNo=du.dutyNo
left join BPMDB.dbo.PW_User u on du.userNo=u.userNo
where sfp.USER_NO is null and u.userNo='{0}' and sf.ROW_ID='{1}'";
            sql = string.Format(sql, userNo, rowId);
            return SysFileBs.GetAllDsBySql(sql);

        }

        #region 工作日历
        public string CreateCalendar(List<SysPeriodEntity> period, List<SysWorkingPeriodEntity> workingPeriod)
        {
            try
            {
                bool re = SysWorkingPeriodBs.CreateCalendar(period, workingPeriod);
                if (re)
                    return "";
                else
                    return "创建工作日历不成功！";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public string UpdateCalendar(SysPeriodEntity period, List<SysWorkingPeriodEntity> workingPeriod)
        {
            try
            {
                bool re = SysWorkingPeriodBs.UpdateCalendar(period, workingPeriod);
                if (re)
                    return "";
                else
                    return "修改工作日历不成功！";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }


        public string DeleteCalendar(SysPeriodEntity period)
        {
            try
            {
                bool re = SysWorkingPeriodBs.DeleteCalendar(period);
                if (re)
                    return "";
                else
                    return "删除工作日历不成功！";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public List<SysPeriodEntity> GetCalendar(int year, int month)
        {
            List<SysPeriodEntity> calendars = SysPeriodBs.GetSysPeriodByMonth(year, month);
            const string Day = "日一二三四五六";
            foreach (SysPeriodEntity c in calendars)
            {
                c.PeriodDate = new DateTime(c.Year, c.Month, c.Day);
                c.DayOfWeek = "星期" + Day[Convert.ToInt16(c.PeriodDate.DayOfWeek)];
            }
            return calendars;

        }

        public List<SysFcEntity> GetFcAllList()
        {
            return SysFcBs.GetSysFcAllList();
        }

        public DataSet GetWorkingPeriod(int year, int month)
        {
            return SysWorkingPeriodBs.GetWorkingPeriod(year, month);
        }
        #endregion

        #region 文件管理
        public FileUploadReturnMessage UploadFileInFileSystem(FileUploadInFileSystemMessage fileEntity)
        {
            FileUploadReturnMessage output = new FileUploadReturnMessage();
            try
            {
                var sysStFile = SysStFileBs.GetSysStFile(new SysStFileEntity { Type = fileEntity.FormName });
                string uploadFolder = sysStFile.Path;
                string savaPath = fileEntity.Type;
                string dateString = DateTime.Now.ToShortDateString() + @"\";
                string fileName = fileEntity.ID + "_" + fileEntity.Name;
                Stream sourceStream = fileEntity.FileData;
                FileStream targetStream = null;

                if (!sourceStream.CanRead)
                {
                    return null;
                }
                if (!savaPath.EndsWith("\\")) savaPath += "\\";
                uploadFolder = uploadFolder + savaPath + dateString;
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                string filePath = Path.Combine(uploadFolder, fileName);
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
                SysFileEntity file = new SysFileEntity
                {
                    Id = fileEntity.ID,
                    IsActive = 1,
                    CreatedBy = fileEntity.UploadBy,
                    CreatedDate = DateTime.Now,
                    UpdatedBy = fileEntity.UploadBy,
                    UpdatedDate = DateTime.Now,
                    FormName = fileEntity.FormName,
                    RowId = fileEntity.RowID,
                    Name = fileEntity.Name,
                    Path = filePath,
                    Type = fileEntity.Type,
                    DeptNo = fileEntity.DeptNo,
                    DocumentNo = fileEntity.DocumentNo,
                    FileNo = fileEntity.FileNo,
                    FileExistsType = fileEntity.FileExistsType,
                    FilePosition = fileEntity.FilePosition,
                    FileStatus = Common.FileUploadStatus.FUS_Draft.ToString(),
                    LogicNo = fileEntity.LogicNo,
                    Ver = fileEntity.Ver,
                    SaveTimerange = fileEntity.SaveTimerange,
                    ControlType = fileEntity.ControlType,
                    InactiveDate = fileEntity.InactiveDate,
                    ActiveDate = fileEntity.ActiveDate

                };
                if (!SysFileBs.InsertSysFile(file))
                {
                    output.FilePath = "UploadFileInFileSystem：添加表单数据失败，请检查数据完整性！";
                }
                return output;
            }
            catch (Exception ex)
            {
                output.FilePath = "UploadFileInFileSystem: " + ex.Message;
                return output;
            }
        }


        public FileUploadReturnMessage UpdateSysFileInFileSystem(FileUploadInFileSystemMessage fileEntity)
        {
            FileUploadReturnMessage output = new FileUploadReturnMessage();
            try
            {
                var sysStFile = SysStFileBs.GetSysStFile(new SysStFileEntity { Type = fileEntity.FormName });
                string uploadFolder = sysStFile.Path;
                string savaPath = fileEntity.Type;
                string dateString = DateTime.Now.ToShortDateString() + @"\";
                string fileName = fileEntity.ID + "_" + fileEntity.Name;
                Stream sourceStream = fileEntity.FileData;
                FileStream targetStream = null;

                if (!sourceStream.CanRead)
                {
                    return null;
                }
                if (!savaPath.EndsWith("\\")) savaPath += "\\";
                uploadFolder = uploadFolder + savaPath + dateString;
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                string filePath = Path.Combine(uploadFolder, fileName);
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
                SysFileEntity file = new SysFileEntity
                {
                    Id = fileEntity.ID,
                    IsActive = 1,
                    CreatedBy = fileEntity.UploadBy,
                    CreatedDate = DateTime.Now,
                    UpdatedBy = fileEntity.UploadBy,
                    UpdatedDate = DateTime.Now,
                    FormName = fileEntity.FormName,
                    RowId = fileEntity.RowID,
                    Name = fileEntity.Name,
                    Path = filePath,
                    Type = fileEntity.Type,
                    DeptNo = fileEntity.DeptNo,
                    DocumentNo = fileEntity.DocumentNo,
                    FileNo = fileEntity.FileNo,
                    FileExistsType = fileEntity.FileExistsType,
                    FilePosition = fileEntity.FilePosition,
                    FileStatus = Common.FileUploadStatus.FUS_Draft.ToString(),
                    LogicNo = fileEntity.LogicNo,
                    Ver = fileEntity.Ver,
                    SaveTimerange = fileEntity.SaveTimerange,
                    ControlType = fileEntity.ControlType,
                    InactiveDate = fileEntity.InactiveDate,
                    ActiveDate = fileEntity.ActiveDate
                };
                if (!SysFileBs.UpdateSysFile(file))
                {
                    output.FilePath = "UpdateSysFileInFileSystem：修改表单数据失败，请检查数据完整性！";
                }
                return output;
            }
            catch (Exception ex)
            {
                output.FilePath = "UpdateSysFileInFileSystem: " + ex.Message;
                return output;
            }
        }


        public DTOSysFileEntitys GetSysFileByLogicNo(string LogicNo)
        {
            DTOSysFileEntitys output = new DTOSysFileEntitys();
            try
            {
                output.result = SysFileBs.GetSysFileByLogicNo(LogicNo);
                return output;
            }
            catch (Exception ex)
            {
                output.ErrorCode = "GetSysFileByLogicNo";
                output.ErrorMessage = ex.Message;
                return output;
            }
        }


        #endregion 文件管理

        #region SysStFile
        public SysStFileEntity GetStFileByKey(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            return SysStFileBs.GetSysStFile(new SysStFileEntity { Id = id });

        }

        public List<SysStFileEntity> GetStFileAllByFormName(string formName)
        {
            if (string.IsNullOrEmpty(formName))
            {
                return Suzsoft.Smart.Data.DataAccess.SelectAll<SysStFileEntity>();
            }
            else
            {
                return Suzsoft.Smart.Data.DataAccess.Select(new SysStFileEntity { Type = formName });
            }
        }

        public string AddStFile(SysStFileEntity source)
        {
            try
            {
                var tmp=Suzsoft.Smart.Data.DataAccess.SelectSingle<SysStFileEntity>(new SysStFileEntity { Type = source.Type });
                if (tmp != null)
                {
                    return source.Type+"已存在，无法新增！";
                }
                source.Id = Guid.NewGuid().ToString();
                source.CreatedDate = DateTime.Now;
                source.UpdatedDate = DateTime.Now;
                source.IsActive = 1;
                if (!System.IO.Directory.Exists(source.Path))
                {
                    System.IO.Directory.CreateDirectory(source.Path);
                }
                if (Suzsoft.Smart.Data.DataAccess.Insert(source))
                {
                    return null;
                }
                else
                {
                    return "插入数据失败！";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public string UpdateStFile(SysStFileEntity source)
        {
            try
            {
                var tmp = Suzsoft.Smart.Data.DataAccess.SelectSingle<SysStFileEntity>(new SysStFileEntity { Type = source.Type });
                if (tmp != null)
                {
                    return source.Type + "已存在，无法修改！";
                }

                source.UpdatedDate = DateTime.Now;
                if (!System.IO.Directory.Exists(source.Path))
                {
                    System.IO.Directory.CreateDirectory(source.Path);
                }
                if (Suzsoft.Smart.Data.DataAccess.Update(source))
                {
                    return null;
                }
                else
                {
                    return "更新数据失败！";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        public bool DelStFile(SysStFileEntity source)
        {
            return Suzsoft.Smart.Data.DataAccess.Delete(source);

        }

        #endregion

        #region 导入模板
        public SysImportTemplateEntity GetImportTemplateByKey(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            return SysImportTemplateBs.GetSysImportTemplate(new SysImportTemplateEntity { Id = id });
        }

        public SysImportTemplateEntity GetImportTemplate(string formName, string type)
        {
            if (string.IsNullOrEmpty(formName) && string.IsNullOrEmpty(type))
                return null;
            return Suzsoft.Smart.Data.DataAccess.SelectSingle<SysImportTemplateEntity>(new SysImportTemplateEntity { FormName = formName, Type = type });

        }

        public List<SysImportTemplateEntity> GetImportTemplateAllByFormName(string formName)
        {
            if (string.IsNullOrEmpty(formName))
            {
                return Suzsoft.Smart.Data.DataAccess.SelectAll<SysImportTemplateEntity>();
            }
            else
            {
                return Suzsoft.Smart.Data.DataAccess.Select(new SysImportTemplateEntity { FormName = formName });
            }
        }

        public bool AddImportTemplate(SysImportTemplateEntity template)
        {
            template.Id = Guid.NewGuid().ToString();
            template.CreatedDate = DateTime.Now;
            template.UpdatedDate = DateTime.Now;
            template.IsActive = 1;
            return Suzsoft.Smart.Data.DataAccess.Insert(template);
        }

        public bool UpdateImportTemplate(SysImportTemplateEntity template)
        {
            template.UpdatedDate = DateTime.Now;
            return Suzsoft.Smart.Data.DataAccess.Update(template);
        }

        public bool DelImportTemplate(SysImportTemplateEntity template)
        {
            return Suzsoft.Smart.Data.DataAccess.Delete(template);

        }

        public ImportTemplateException ImportTemplateData(DataSet source, string formName)
        {
            ImportTemplateException exp = new ImportTemplateException();
            switch (formName)
            {
                case "frmManageUser":
                    exp = ImportUserData(source);
                    return exp;
                case "frmManageDept":
                    exp = ImportDeptData(source);
                    return exp;
                case "frmManageDuty":
                    exp = ImportDutyData(source);
                    return exp;
                case "frmManageCodeRule":
                    exp = ImportCodeRuleData(source);
                    return exp;
                case "frmManageCommonItem":
                    exp = ImportCommonItemData(source);
                    return exp;
                case "frmManageProductionType":
                    exp = ImportProductTypeData(source);
                    return exp;
                default:
                    return exp;
            }
        }

        private ImportTemplateException ImportUserData(DataSet source)
        {
            ImportTemplateException exp = new ImportTemplateException();
            List<PW_User> users = new List<PW_User>();
            string connectionString = BPM.Base.Tools.MyConfig.getConnection("myconstring");
            PWDBDataContext pwdb = new PWDBDataContext(connectionString);
            for (int i = 0; i < source.Tables[0].Rows.Count; i++)
            {
                PW_User user = new PW_User();
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][0].ToString()))
                {
                    var tmp = pwdb.PW_User.Where(a => a.userNo == source.Tables[0].Rows[i][0].ToString()).ToList();
                    if (tmp.Count != 0)
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'工号：{1} 已存在！";
                        str = string.Format(str, i, source.Tables[0].Rows[i][0].ToString());
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        user.userNo = source.Tables[0].Rows[i][0].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][1].ToString()))
                {
                    user.firstName = source.Tables[0].Rows[i][1].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][2].ToString()))
                {
                    user.lastName = source.Tables[0].Rows[i][2].ToString();
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][3].ToString()))
                {
                    user.password = source.Tables[0].Rows[i][3].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[3].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][4].ToString()))
                {
                    user.alias = source.Tables[0].Rows[i][4].ToString();
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][5].ToString()))
                {
                    user.sex = source.Tables[0].Rows[i][5].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[5].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!source.Tables[0].Rows[i][6].Equals("1-1-00"))
                {
                    user.birthDate = (DateTime)source.Tables[0].Rows[i][6];
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][7].ToString()))
                {
                    user.phone = source.Tables[0].Rows[i][7].ToString();
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][8].ToString()))
                {
                    user.email = source.Tables[0].Rows[i][8].ToString();
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][9].ToString()))
                {
                    user.showRule = source.Tables[0].Rows[i][9].ToString();
                }
                if (string.IsNullOrEmpty(source.Tables[0].Rows[i][10].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[10].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!Common.CommonFunctions.IsNumeric(source.Tables[0].Rows[i][10].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[10].ColumnName + "'数据必须为数字类型！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!(Convert.ToInt32(source.Tables[0].Rows[i][10]) == 0 || Convert.ToInt32(source.Tables[0].Rows[i][10]) == 1))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[10].ColumnName + "'数据必须为0或1！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else
                {
                    user.isFreeze = Convert.ToInt32(source.Tables[0].Rows[i][10]);
                }
                user.ID = Guid.NewGuid();
                users.Add(user);

            }
            try
            {
                pwdb.PW_User.InsertAllOnSubmit(users);
                pwdb.SubmitChanges();
                return null;
            }
            catch (Exception ex)
            {
                exp.SysExpInfo = ex.Message;
                return exp;
            }
        }

        private ImportTemplateException ImportDeptData(DataSet source)
        {
            ImportTemplateException exp = new ImportTemplateException();
            List<PW_Department> depts = new List<PW_Department>();
            string connectionString = BPM.Base.Tools.MyConfig.getConnection("myconstring");
            PWDBDataContext pwdb = new PWDBDataContext(connectionString);
            for (int i = 0; i < source.Tables[0].Rows.Count; i++)
            {
                PW_Department dept = new PW_Department();
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][0].ToString()))
                {
                    dept.departmentName = source.Tables[0].Rows[i][0].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][1].ToString()))
                {
                    var tmp = pwdb.PW_Department.Where(a => a.departmentNo == source.Tables[0].Rows[i][1].ToString()).ToList();
                    if (tmp.Count != 0)
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'部门：{1} 已存在！";
                        str = string.Format(str, i, source.Tables[0].Rows[i][1].ToString());
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        dept.departmentNo = source.Tables[0].Rows[i][1].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][2].ToString()))
                {
                    dept.parentDepartment = source.Tables[0].Rows[i][2].ToString();
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][3].ToString()))
                {
                    dept.departmentType = source.Tables[0].Rows[i][3].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[3].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][4].ToString()))
                {
                    dept.departmentDescription = source.Tables[0].Rows[i][4].ToString();
                }
                if (string.IsNullOrEmpty(source.Tables[0].Rows[i][5].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[5].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!Common.CommonFunctions.IsNumeric(source.Tables[0].Rows[i][5].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[5].ColumnName + "'数据必须为数字类型！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!(Convert.ToInt32(source.Tables[0].Rows[i][5]) == 0 || Convert.ToInt32(source.Tables[0].Rows[i][5]) == 1))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[5].ColumnName + "'数据必须为0或1！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else
                {
                    dept.isFreeze = Convert.ToInt32(source.Tables[0].Rows[i][5]);
                }

                if (string.IsNullOrEmpty(source.Tables[0].Rows[i][6].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[6].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!Common.CommonFunctions.IsNumeric(source.Tables[0].Rows[i][6].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[6].ColumnName + "'数据必须为数字类型！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!(Convert.ToInt32(source.Tables[0].Rows[i][6]) == 0 || Convert.ToInt32(source.Tables[0].Rows[i][6]) == 1 || Convert.ToInt32(source.Tables[0].Rows[i][6]) == 2))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[6].ColumnName + "'数据必须为0、1或2！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else
                {
                    dept.departmentWeight = Convert.ToInt32(source.Tables[0].Rows[i][6]);
                }
                dept.ID = Guid.NewGuid();
                dept.departmentCreateTime = DateTime.Now;

                depts.Add(dept);

            }
            try
            {
                pwdb.PW_Department.InsertAllOnSubmit(depts);
                pwdb.SubmitChanges();
                return null;
            }
            catch (Exception ex)
            {
                exp.SysExpInfo = ex.Message;
                return exp;
            }
        }

        private ImportTemplateException ImportDutyData(DataSet source)
        {
            ImportTemplateException exp = new ImportTemplateException();
            List<PW_Duty> dutys = new List<PW_Duty>();
            string connectionString = BPM.Base.Tools.MyConfig.getConnection("myconstring");
            PWDBDataContext pwdb = new PWDBDataContext(connectionString);
            for (int i = 0; i < source.Tables[0].Rows.Count; i++)
            {
                PW_Duty duty = new PW_Duty();
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][0].ToString()))
                {
                    duty.dutyName = source.Tables[0].Rows[i][0].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][1].ToString()))
                {
                    var tmp = pwdb.PW_Duty.Where(a => a.dutyNo == source.Tables[0].Rows[i][1].ToString()).ToList();
                    if (tmp.Count != 0)
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'职位：{1} 已存在！";
                        str = string.Format(str, i, source.Tables[0].Rows[i][1].ToString());
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        duty.dutyNo = source.Tables[0].Rows[i][1].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][2].ToString()))
                {
                    duty.parentDuty = source.Tables[0].Rows[i][2].ToString();
                }
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][3].ToString()))
                {
                    duty.dutyDescription = source.Tables[0].Rows[i][3].ToString();
                }

                if (string.IsNullOrEmpty(source.Tables[0].Rows[i][4].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!Common.CommonFunctions.IsNumeric(source.Tables[0].Rows[i][4].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'数据必须为数字类型！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!(Convert.ToInt32(source.Tables[0].Rows[i][4]) == 0 || Convert.ToInt32(source.Tables[0].Rows[i][4]) == 1))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'数据必须为0或1！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else
                {
                    duty.isFreeze = Convert.ToInt32(source.Tables[0].Rows[i][4]);
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][5].ToString()))
                {
                    duty.dutyType = source.Tables[0].Rows[i][5].ToString();
                }

                duty.ID = Guid.NewGuid();
                duty.dutyCreateTime = DateTime.Now;
                dutys.Add(duty);
            }
            try
            {
                pwdb.PW_Duty.InsertAllOnSubmit(dutys);
                pwdb.SubmitChanges();
                return null;
            }
            catch (Exception ex)
            {
                exp.SysExpInfo = ex.Message;
                return exp;
            }

        }

        private ImportTemplateException ImportCodeRuleData(DataSet source)
        {
            ImportTemplateException exp = new ImportTemplateException();
            List<MstCodeRuleEntity> rules = new List<MstCodeRuleEntity>();
            string connectionString = BPM.Base.Tools.MyConfig.getConnection("myconstring");
            PWDBDataContext pwdb = new PWDBDataContext(connectionString);
            for (int i = 0; i < source.Tables[0].Rows.Count; i++)
            {
                MstCodeRuleEntity rule = new MstCodeRuleEntity();
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][0].ToString()))
                {
                    var tmp = Suzsoft.Smart.Data.DataAccess.SelectSingle<MstCodeRuleEntity>(new MstCodeRuleEntity { CodeType = source.Tables[0].Rows[i][0].ToString() });
                    if (tmp != null)
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'数据：{1} 已存在！";
                        str = string.Format(str, i, source.Tables[0].Rows[i][0].ToString());
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        rule.CodeType = source.Tables[0].Rows[i][0].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][1].ToString()))
                {
                    rule.CodeName = source.Tables[0].Rows[i][1].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][2].ToString()))
                {
                    rule.CodePrefix = source.Tables[0].Rows[i][2].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[2].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][3].ToString()))
                {
                    rule.Remark = source.Tables[0].Rows[i][3].ToString();
                }

                if (string.IsNullOrEmpty(source.Tables[0].Rows[i][4].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!Common.CommonFunctions.IsNumeric(source.Tables[0].Rows[i][4].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'数据必须为数字类型！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else
                {
                    rule.CurrentValue = Convert.ToInt32(source.Tables[0].Rows[i][4]);
                }
                rule.CodeDateFormat = "yyyyMMdd";
                rule.CodeSeqLen = 3;
                rule.CurrentDay = DateTime.Now.ToString("yyyyMMdd");

                rules.Add(rule);
            }
            try
            {
                if (Suzsoft.Smart.Data.DataAccess.Insert(rules))
                {
                    return null;
                }
                else
                {
                    exp.CustomExpInfo = "保存数据失败！";
                    return exp;
                }
            }
            catch (Exception ex)
            {
                exp.SysExpInfo = ex.Message;
                return exp;
            }

        }

        private ImportTemplateException ImportCommonItemData(DataSet source)
        {
            ImportTemplateException exp = new ImportTemplateException();
            List<MstCommonItemEntity> items = new List<MstCommonItemEntity>();
            string connectionString = BPM.Base.Tools.MyConfig.getConnection("myconstring");
            PWDBDataContext pwdb = new PWDBDataContext(connectionString);
            for (int i = 0; i < source.Tables[0].Rows.Count; i++)
            {
                MstCommonItemEntity item = new MstCommonItemEntity();
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][0].ToString()))
                {
                    var tmp = Suzsoft.Smart.Data.DataAccess.SelectSingle<MstCommonItemEntity>(new MstCommonItemEntity { ItemCode = source.Tables[0].Rows[i][0].ToString() });
                    if (tmp != null)
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'数据：{1} 已存在！";
                        str = string.Format(str, i, source.Tables[0].Rows[i][0].ToString());
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        item.ItemCode = source.Tables[0].Rows[i][0].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][1].ToString()))
                {
                    item.ItemName = source.Tables[0].Rows[i][1].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[1].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][2].ToString()))
                {
                    item.ItemType = source.Tables[0].Rows[i][2].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[2].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][3].ToString()))
                {
                    item.ItemValue = source.Tables[0].Rows[i][3].ToString();
                }

                if (string.IsNullOrEmpty(source.Tables[0].Rows[i][4].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!Common.CommonFunctions.IsNumeric(source.Tables[0].Rows[i][4].ToString()))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'数据必须为数字类型！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else if (!(Convert.ToInt32(source.Tables[0].Rows[i][4]) == 0 || Convert.ToInt32(source.Tables[0].Rows[i][4]) == 1))
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'数据必须为0或1！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }
                else
                {
                    item.IsDeleted = Convert.ToInt32(source.Tables[0].Rows[i][4]);
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][5].ToString()))
                {
                    item.Remark = source.Tables[0].Rows[i][5].ToString();
                }

                items.Add(item);
            }
            try
            {
                if (Suzsoft.Smart.Data.DataAccess.Insert(items))
                {
                    return null;
                }
                else
                {
                    exp.CustomExpInfo = "保存数据失败！";
                    return exp;
                }
            }
            catch (Exception ex)
            {
                exp.SysExpInfo = ex.Message;
                return exp;
            }

        }

        private ImportTemplateException ImportProductTypeData(DataSet source)
        {
            ImportTemplateException exp = new ImportTemplateException();
            List<MstProductTypeEntity> types = new List<MstProductTypeEntity>();
            string connectionString = BPM.Base.Tools.MyConfig.getConnection("myconstring");
            PWDBDataContext pwdb = new PWDBDataContext(connectionString);
            for (int i = 0; i < source.Tables[0].Rows.Count; i++)
            {
                MstProductTypeEntity type = new MstProductTypeEntity();
                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][0].ToString()))
                {
                    var tmp = Suzsoft.Smart.Data.DataAccess.SelectSingle<MstProductTypeEntity>(new MstProductTypeEntity { ProductTypeId = source.Tables[0].Rows[i][0].ToString() });
                    if (tmp != null)
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'数据：{1} 已存在！";
                        str = string.Format(str, i, source.Tables[0].Rows[i][0].ToString());
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        type.ProductTypeId = source.Tables[0].Rows[i][0].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[0].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][1].ToString()))
                {
                    type.ParentTypeId = source.Tables[0].Rows[i][1].ToString();
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][2].ToString()))
                {
                    type.ProductTypeCode = source.Tables[0].Rows[i][2].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[2].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][3].ToString()))
                {
                    type.ProductTypeName = source.Tables[0].Rows[i][3].ToString();
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[3].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][4].ToString()))
                {
                    if (!(source.Tables[0].Rows[i][4].ToString().Equals("CG01") || source.Tables[0].Rows[i][4].ToString().Equals("CG02")))
                    {
                        string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'数值错误，只能为:CG01或CG02！";
                        str = string.Format(str, i);
                        exp.DataCheckInfo = str;
                        return exp;
                    }
                    else
                    {
                        type.Category = source.Tables[0].Rows[i][4].ToString();
                    }
                }
                else
                {
                    string str = "第{0}行,列'" + source.Tables[0].Columns[4].ColumnName + "'不能为空！";
                    str = string.Format(str, i);
                    exp.DataCheckInfo = str;
                    return exp;
                }

                if (!string.IsNullOrEmpty(source.Tables[0].Rows[i][5].ToString()))
                {
                    type.Description = source.Tables[0].Rows[i][5].ToString();
                }

                types.Add(type);
            }
            try
            {
                if (Suzsoft.Smart.Data.DataAccess.Insert(types))
                {
                    return null;
                }
                else
                {
                    exp.CustomExpInfo = "保存数据失败！";
                    return exp;
                }
            }
            catch (Exception ex)
            {
                exp.SysExpInfo = ex.Message;
                return exp;
            }

        }

        #endregion

    }

}

